<template>
  <NavBar>
    <template #default> 确认订单 </template>
  </NavBar>
  <div class="order-confirm-page">
    <el-card class="box-card">
      <h3>商品清单</h3>
      <el-table
        :data="selectedCartItems"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="productName" label="商品名称" />
        <el-table-column prop="price" label="单价" width="100">
          <template #default="{ row }">￥{{ row.price.toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="80" />
        <el-table-column label="小计" width="100">
          <template #default="{ row }"
            >￥{{ (row.price * row.quantity).toFixed(2) }}</template
          >
        </el-table-column>
      </el-table>

      <h3 style="margin-top: 20px">选择收货地址</h3>
      <el-radio-group v-model="selectedAddressId">
        <el-radio
          v-for="address in addressList"
          :key="address.addressId"
          :value="address.addressId"
          border
          style="display: block; margin-bottom: 10px"
        >
          {{ address.receiverName }} - {{ address.detailAddress }} ({{
            address.phone
          }})
        </el-radio>
      </el-radio-group>
      <el-button
        v-if="addressList == null || addressList.length === 0"
        type="text"
        @click="goToAddressManager"
      >
        还没有收货地址？去添加一个
      </el-button>
      <el-button v-else type="text" @click="goToAddressManager">
        新增地址
      </el-button>

      <h3 style="margin-top: 20px">选择支付方式</h3>
      <el-radio-group v-model="paymentType">
        <el-radio :value="1" border>
          <img
            src="@/assets/alipay.png"
            alt="支付宝"
            style="height: 24px; vertical-align: middle"
          />
          支付宝
        </el-radio>
        <el-radio :value="2" border disabled>
          <img
            src="@/assets/weixinpay.png"
            alt="微信支付"
            style="height: 24px; vertical-align: middle"
          />
          微信支付 (暂不支持)
        </el-radio>
      </el-radio-group>

      <h3 style="margin-top: 20px">订单备注</h3>
      <el-input
        v-model="remark"
        placeholder="请输入订单备注"
        type="textarea"
        :rows="2"
      />

      <div class="confirm-footer">
        <div class="total-summary">
          商品总价：<span class="price-text"
            >￥{{ totalPrice.toFixed(2) }}</span
          >
        </div>
        <el-button
          type="primary"
          @click="submitOrder"
          :disabled="!selectedAddressId || !paymentType || loading"
        >
          提交订单
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import NavBar from "../../components/common/NavBar.vue";
import { ref, onMounted, computed, onActivated } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useCartStore } from "@/stores/cartStore";
import { getAddressList, createOrder } from "@/api/OrderApi";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();
const cartStore = useCartStore();

const cartIds = JSON.parse(route.query.cartIds || "[]");
const selectedCartItems = ref([]);
const addressList = ref([]);
const selectedAddressId = ref(null);
const paymentType = ref(1);
const remark = ref("尽快送货");
const loading = ref(false);

const totalPrice = computed(() =>
  selectedCartItems.value.reduce(
    (sum, item) => sum + item.price * item.quantity,
    0
  )
);

// 新增一个函数来封装数据加载逻辑
const loadData = async () => {
  loading.value = true;
  try {
    // 步骤1: 重新获取最新的购物车数据
    await cartStore.fetchCartItems();
    // 从 cartStore 中筛选出选中的商品
    selectedCartItems.value = cartStore.items.filter((item) =>
      cartIds.includes(item.cartId)
    );

    // 获取地址列表
    const addressRes = await getAddressList();
    if (addressRes.data.code === 1) {
      addressList.value = addressRes.data.data;
      if (addressList.value != null && addressList.value.length > 0) {
        const defaultAddress = addressList.value.find(
          (addr) => addr.isDefault === 1
        );
        if (defaultAddress) {
          selectedAddressId.value = defaultAddress.addressId;
        } else {
          selectedAddressId.value = addressList.value[0].addressId;
        }
      }
    } else {
      ElMessage.error("获取收货地址失败");
    }
  } catch (error) {
    console.log(error);
    ElMessage.error("加载订单信息失败" + error);
  } finally {
    loading.value = false;
  }
};

// 在组件首次挂载时调用数据加载
onMounted(() => {
  loadData();
});

// 使用 onActivated 钩子，在组件从缓存中被激活时重新加载数据
// 这需要 OrderConfirm.vue 被 <keep-alive> 包裹
onActivated(() => {
  loadData();
});

const submitOrder = async () => {
  if (!selectedAddressId.value) {
    ElMessage.warning("请选择一个收货地址");
    return;
  }
  if (!paymentType.value) {
    ElMessage.warning("请选择支付方式");
    return;
  }
  if (selectedCartItems.value.length <= 0) {
    ElMessage.warning("请选择商品");
    return;
  }
  loading.value = true;
  try {
    // 1. 构建 OrdersDTO 对象
    const ordersDTO = {
      addressId: selectedAddressId.value,
      paymentType: paymentType.value,
      remark: remark.value,
    };

    // 2. 构建 List<OrdersItemsDTO> 数组
    const ordersItemsDTOList = selectedCartItems.value.map((item) => ({
      productId: item.productId,
      quantity: item.quantity,
      price: item.price,
    }));

    const cartIds = selectedCartItems.value.map((item) => item.cartId);

    // 3. 将这两个对象作为请求体发送给后端
    // 注意: 后端如果使用了 @RequestBody List<OrdersItemsDTO> orderItemsDTOList，
    // 需要确保请求体能正确解析。
    // 在这里，我们将两个对象放在一个请求体中，键名与后端参数名保持一致
    const requestData = {
      ordersDTO: ordersDTO,
      orderItemsDTOList: ordersItemsDTOList,
      cartIds: cartIds,
    };
    const orderRes = await createOrder(requestData);
    if (orderRes.code === 1) {
      // 可以选择性地清除购物车中已结算的商品
      cartStore.fetchCartItems();
      ElMessage.success("订单创建成功，即将跳转到支付页面");
      router.push({
        name: "OrderPay",
        params: { orderId: orderRes.data.id },
      });
    }
  } catch (error) {
    ElMessage.error("提交订单失败，请稍后再试");
  } finally {
    loading.value = false;
  }
};

const goToAddressManager = () => {
  router.push("/orders/address");
};
</script>

<style scoped>
.order-confirm-page {
  max-width: 900px;
  margin: 20px auto;
}
.card-header {
  font-size: 18px;
  font-weight: bold;
}
h3 {
  border-left: 4px solid #ff5000;
  padding-left: 8px;
  margin: 15px 0;
  font-size: 16px;
}
.confirm-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px;
  border-top: 1px solid #ebeef5;
}
.total-summary {
  margin-right: 20px;
}
.price-text {
  color: #ff5000;
  font-weight: bold;
  font-size: 18px;
}
</style>